/**
 * @Author: Jiang Zhongxun
 * @Date: 2025-02-18 21:40:18
 * @FilePath: \CAR_REG\Dri\Dri_TIM.c
 * @Description: 定时器相关的驱动
 * @Copyright (c) 2025 by JiangZhongxun, All Rights Reserved.
 */
#include "Dri_TIM.h"

/**
 * @description: 定时器4的初始化：CH3、CH4输出PWM
 * @param {*} 无参
 * @return {*} 无返回值
 */
void Dri_TIM4_Init(void)
{
    /* 时钟、GPIO、定时器基本配置、PWM模式 */

    // 1. 开启时钟
    // 1.1 定时器的时钟
    RCC->APB1ENR |= RCC_APB1ENR_TIM4EN;
    // 1.2 GPIO的时钟
    RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;

    // 2. 设置GPIO的复用推挽输出 PB8、PB9 CNF=10、MODE=11
    GPIOB->CRH |= GPIO_CRH_MODE8;
    GPIOB->CRH |= GPIO_CRH_CNF8_1;
    GPIOB->CRH &= ~GPIO_CRH_CNF8_0;
    GPIOB->CRH |= GPIO_CRH_MODE9;
    GPIOB->CRH |= GPIO_CRH_CNF9_1;
    GPIOB->CRH &= ~GPIO_CRH_CNF9_0;

    // 3. 定时器基本通用配置
    // PWM输出频率 = 72M时钟频率 / (预分频值 * 自动重装载值) = 10K
    // 3.1 预分频寄存器配置
    TIM4->PSC = 1 - 1;
    // 3.2 自动重装载寄存器配置
    TIM4->ARR = 7200 - 1;
    // 3.3 计数器的计数方向，0=向上，1=向下
    TIM4->CR1 &= ~TIM_CR1_DIR;

    // 4. PWM模式配置：通道3
    // 4.1 配置通道3的捕获比较寄存器
    TIM4->CCR3 = 0;
    // 4.2 把通道3配置为输出，CCMR2_CC3S=00
    TIM4->CCMR2 &= ~TIM_CCMR2_CC3S;
    // 4.3 配置通道的输出比较模式为PWM模式1，CCMR2_OC3M=110
    TIM4->CCMR2 |= TIM_CCMR2_OC3M_2;
    TIM4->CCMR2 |= TIM_CCMR2_OC3M_1;
    TIM4->CCMR2 &= ~TIM_CCMR2_OC3M_0;
    // 4.4 使能通道3，CCER_CC3E=1
    TIM4->CCER |= TIM_CCER_CC3E;
    // 4.5 设置通道的极性，0=高电平有效，1=低电平有效
    TIM4->CCER &= ~TIM_CCER_CC3P;

    // 5. PWM模式配置：通道4
    // 5.1 配置通道4的捕获比较寄存器
    TIM4->CCR4 = 0;
    // 5.2 把通道4配置为输出，CCMR2_CC4S=00
    TIM4->CCMR2 &= ~TIM_CCMR2_CC4S;
    // 5.3 配置通道的输出比较模式为PWM模式1，CCMR2_OC4M=110
    TIM4->CCMR2 |= TIM_CCMR2_OC4M_2;
    TIM4->CCMR2 |= TIM_CCMR2_OC4M_1;
    TIM4->CCMR2 &= ~TIM_CCMR2_OC4M_0;
    // 5.4 使能通道4，CCER_CC4E=1
    TIM4->CCER |= TIM_CCER_CC4E;
    // 5.5 设置通道的极性，0=高电平有效，1=低电平有效
    TIM4->CCER &= ~TIM_CCER_CC4P;

    // 6. 启动定时器
    TIM4->CR1 |= TIM_CR1_CEN;
}
